package tech.eyao.hs60x.serviceImpl;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.eyao.hs60x.common.ReturnCode;
import tech.eyao.hs60x.converts.ApprovalConvert;
import tech.eyao.hs60x.dao.AccountRelationDao;
import tech.eyao.hs60x.dao.ApprovalDao;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.enums.ApprovalStatus;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.enums.RoleType;
import tech.eyao.hs60x.model.domain.AccountRelationDO;
import tech.eyao.hs60x.model.domain.ApprovalDO;
import tech.eyao.hs60x.service.ApprovalService;
import tech.eyao.hs60x.vo.ApprovalPageQuery;

/**
 * 绑定申请实现类
 * 
 * @author hejian
 * @date 2018年1月12日 下午2:55:09
 */
@Service
public class ApprovalServiceImpl implements ApprovalService {

    private static final Logger logger = LoggerFactory.getLogger(ApprovalServiceImpl.class);
    @Autowired
    private ApprovalDao         approvalDao;
    @Autowired
    private AccountRelationDao  accountRelationDao;

    @Override
    public BaseResult getListByPage(ApprovalPageQuery pageQuery) {
        BaseResult baseResult = new BaseResult();

        if (null == pageQuery) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
        }

        // 当前用户是否为管理用户
        if (!accountRelationDao.isAdmin(pageQuery.getUserId())) {
            return BaseResult.isBussinessFail("非管理登录设备");
        }

        try {
            List<ApprovalDO> approvalDOs = approvalDao.getListByPage(pageQuery);
            baseResult.code = ReturnCode.C_SUCCESS_CODE;
            baseResult.message = ReturnCode.SUCCESS_CODE.getDesc();

            baseResult.data = ApprovalConvert.convert(approvalDOs);
        } catch (Exception e) {
            logger.error("[ApprovalService getListByPage error.]", e);
            return BaseResult.isDeFaultFailure();

        }
        return baseResult;
    }

    @Override
    public BaseResult agree(Long id, Long userId,String action) {
        BaseResult baseResult = new BaseResult();
        Boolean IS_AllOW = true;
        try {
        	 // 当前id记录是否存在
            ApprovalDO approvalDO = approvalDao.selectByPrimaryKey(id);
            if (null == approvalDO) {
                return BaseResult.isBussinessFail("审批记录不存在");
            }
            
            if (approvalDO.getStatus().intValue() == ApprovalStatus.YES.getValue()) {
                return BaseResult.isBussinessFail("已经审批");
            }
            // 手表是否未绑定管理员
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountAdminByWatchId(approvalDO.getWatchId());
            if (null == accountRelationDO) {
                return BaseResult.isBussinessFail("手表:" + approvalDO.getWatchId() + "未设置管理员");
            }
            // 手表对应的管理员ID 是否和userId相等 --EQUALS
            if (approvalDO.getOwnId().longValue() != userId.longValue()) {
                return BaseResult.isBussinessFail("当前用户非管理员，无权限审批！");
            }
            if (action.toUpperCase().equals(ApprovalStatus.REFUSE.getKey())) {
                IS_AllOW = false;
            }
            //获取审批状态
            approvalDO.setStatus(ApprovalStatus.getValueByKey(action).getValue());
            boolean result = approvalDao.updateByPrimaryKey(approvalDO);

            if (IS_AllOW & result) {
                AccountRelationDO currentRelationDO = new AccountRelationDO();
                currentRelationDO.setRelationBusType(approvalDO.getType());
                currentRelationDO.setRelationFunId(approvalDO.getWatchId());
                currentRelationDO.setRelationId(approvalDO.getFriendId());
                currentRelationDO.setRelationName(approvalDO.getFriendNickName());
                currentRelationDO.setRoleCode(RoleType.NORMALUSER.getCode());
                if(null == accountRelationDao.getAccountRelation(currentRelationDO.getRelationId(), currentRelationDO.getRelationFunId())) {
                	boolean update = accountRelationDao.insert(currentRelationDO);
                    if (!update) {
                        approvalDO.setStatus(ApprovalStatus.NO.getValue());
                        approvalDao.updateByPrimaryKey(approvalDO);
                        throw new RuntimeException("系统操作失败");
                    }
                }
            }
		} catch (Exception e) {
			logger.error("[ApprovalService agree error .]", e);
		}
        baseResult.code = ReturnCode.C_SUCCESS_CODE;
        baseResult.message = ReturnCode.SUCCESS_CODE.getDesc();
        return baseResult;
    }
}
